<template>
  <div class="admin-layout">
    <el-container class="layout-container">
      <!-- 侧边栏 -->
      <el-aside :width="isCollapse ? '64px' : '220px'" class="layout-aside">
        <div class="logo" :class="{ 'logo-collapse': isCollapse }">
          <!-- <img src="/favicon.ico" alt="Logo" class="logo-img" /> -->
          <span v-show="!isCollapse" class="logo-text">通用后台管理系统</span>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="true"
          class="layout-menu"
          router
        >
          <template v-for="menu in menuList" :key="menu.id">
            <el-sub-menu v-if="menu.children && menu.children.length" :index="menu.path">
              <template #title>
                <el-icon><component :is="menu.icon" /></el-icon>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item
                v-for="subMenu in menu.children"
                :key="subMenu.id"
                :index="subMenu.path"
              >
                <el-icon><component :is="subMenu.icon" /></el-icon>
                <span>{{ subMenu.name }}</span>
              </el-menu-item>
            </el-sub-menu>
            
            <el-menu-item v-else :index="menu.path">
              <el-icon><component :is="menu.icon" /></el-icon>
              <span>{{ menu.name }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-container class="layout-main">
        <!-- 顶部导航栏 -->
        <el-header class="layout-header">
          <div class="header-left">
            <el-icon class="collapse-btn" @click="toggleCollapse">
              <Expand v-if="isCollapse" />
              <Fold v-else />
            </el-icon>
            
            <!-- 面包屑导航 -->
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.path" :to="item.path">
                {{ item.name }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <!-- 用户菜单 -->
            <el-dropdown class="user-dropdown" @command="handleUserCommand">
              <div class="user-info el-dropdown-link">
                <el-avatar :size="32">
                  <img :src="getAvatarUrl(userInfo.avatar) || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                </el-avatar>
                <!--   -->
                <span class="username"> {{ userInfo.username }}</span>
                <el-icon><CaretBottom /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>个人中心
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <!-- 主内容区 -->
        <el-main class="layout-content">
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted ,reactive} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMenuStore } from '@/stores/menu'
import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/stores/user'
import { useRoleStore } from '@/stores/role'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Expand,
  Fold,
  CaretBottom,
  User,
  SwitchButton
} from '@element-plus/icons-vue'
const roleStore=useRoleStore()
const route = useRoute()
const router = useRouter()
const menuStore = useMenuStore()
const authStore = useAuthStore()
const userStore = useUserStore()
// 检查登录状态
const checkAuthStatus = () => {
  if (!authStore.isLoggedIn) {
    // 未登录，跳转到登录页
    router.push('/login')
    return false
  }
  return true
}
const parentMenuOptions = ref([
  {
    id: null,
    name: '顶级菜单',
    children: []
  }
])

// 构建父级菜单选项（排除当前菜单及其子菜单）
const buildParentOptions = (data, excludeId = null) => {
  const result = []

  // 递归查找所有子菜单ID
  const getAllChildIds = (menu) => {
    const ids = [menu.id]
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        ids.push(...getAllChildIds(child))
      })
    }
    return ids
  }

  data.forEach(item => {
    // 如果当前菜单是需要排除的菜单或其子菜单，跳过
    if (excludeId && getAllChildIds(item).includes(excludeId)) {
      return
    }

    const option = {
      id: item.id,
      name: item.name,
      children: item.children && item.children.length > 0 ? buildParentOptions(item.children, excludeId) : []
    }
    result.push(option)
  })
  return result
}
// 响应式数据
const isCollapse = ref(false)

// 计算属性
const userInfo = computed(() => authStore.userInfo)
const menuget =async()=>{return await menuStore.getmenutree()}
let dangermenu ={}

const menuList = ref()
// const menuList = computed(() => menuStore.menuList)
const activeMenu = computed(() => route.path)
const breadcrumbs = computed(() => {
  // 根据当前路由生成面包屑
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    name: item.meta.title,
    path: item.path
  }))
})

// 方法
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // user.value=userInfo.value
        await authStore.logout(userInfo.value)
        router.push('/login')
        ElMessage.success('已安全退出')
      } catch {
        // 用户取消
      }
      break
  }
}

const getAvatarUrl = (avatar) => {
  console.log('AdminLayout - 原始头像路径:', avatar)
  
  if (!avatar) {
    console.log('AdminLayout - 没有头像，返回空字符串')
    return ''
  }
  
  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    console.log('AdminLayout - 完整URL，直接返回:', avatar)
    return avatar
  }
  
  // 如果是相对路径，加上后端基础URL
  const baseUrl = 'http://admin-lusiyi.ijelly.cn'
  let fullUrl
  if (avatar.startsWith('/')) {
    fullUrl = baseUrl + avatar
  } else {
    fullUrl = baseUrl + '/' + avatar
  }
  
  console.log('AdminLayout - 构建的完整URL:', fullUrl)
  return fullUrl
}

// 生命周期
onMounted(async () => {
   const menuItems = ref([]); // 用于存储菜单数据
    //  const roles = ref([/* 假设这里是你从 Vuex 或其他地方获取的角色数据 */]);



    const roles = JSON.parse(localStorage.getItem('userInfo')).roles

    // 获取到用户角色名
    console.log(roles[0].name);
    // 获取到角色权限
    const role = await roleStore.getRoles({ keyword: roles[0].name });
    const roleId = role.roles[0].id;
    // 使用 roleId 查询才可以获取到树形
    const item = await roleStore.getsingle(roleId);
    console.log(roleId);
    console.log(item.menus);
    // 更新 menuItems
    menuItems.value = item.menus;
    // } catch (error) {
    //   console.error('获取菜单数据失败:', error);
    // }

    const menuMap = new Map(menuItems.value.map(item => [item.id, { ...item, children: [] }]));

    // 遍历数组，构建树形结构
    const treeData = reactive([]);
    menuItems.value.forEach(item => {
      if (item.parentId === null) {
        // 如果 parentId 为 null，表示这是顶级菜单
        treeData.push(menuMap.get(item.id));
      } else {
        // 如果 parentId 不为 null，找到对应的父菜单项，并将其添加到父菜单项的 children 中
        const parentItem = menuMap.get(item.parentId);
        if (parentItem) {
          parentItem.children.push(menuMap.get(item.id));
        }
      }
    });
    // tableData.value = treeData
    // displayData.value = treeData

    // 构建父级菜单选项（初始加载时不排除任何菜单）
    parentMenuOptions.value = [
      { id: null, name: '顶级菜单', children: [] },
      ...buildParentOptions(treeData)
    ]
  // 检查登录状态
  const res =(await menuStore.getMenu()).menus
  console.log(res);
  
  //定一个值保存菜单列表数据，防止丢失
  dangermenu =res
//  
  menuList.value=treeData
  
  if (!checkAuthStatus()) {
    return // 未登录，已跳转到登录页，不继续执行
  }
  
  try {
    // 获取最新的用户信息（包括头像）
    const latestUserInfo = await userStore.getUserProfile()
    authStore.setUserInfo(latestUserInfo)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果获取失败，继续使用缓存的用户信息
  }
  
  // 加载菜单数据
//  const ress= await menuStore.loadMenuList()
//  console.log(ress);
 
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.layout-container {
  height: 100%;
}

.layout-aside {
  background-color: #91b5e2;
  transition: width 0.3s;
}

.logo {
  display: flex;
  align-items: center;
  padding: 20px 16px;
  color: #fff;
  transition: padding 0.3s;
}

.logo-collapse {
  padding: 20px 8px;
  justify-content: center;
}

.logo-img {
  width: 32px;
  height: 32px;
  margin-right: 8px;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  white-space: nowrap;
}

.layout-menu {
  border: none;
  background-color: #91b5e2;
}

.layout-menu :deep(.el-menu-item),
.layout-menu :deep(.el-sub-menu__title) {
  color: #254e80;
}

.layout-menu :deep(.el-menu-item:hover),
.layout-menu :deep(.el-sub-menu__title:hover) {
  background-color: #bedbff;
  color: #273339;
}

.layout-menu :deep(.el-menu-item.is-active) {
  background-color: #409eff;
  color: #fff;
}

.layout-header {
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 20px;
  color: #5a5e66;
}

.collapse-btn:hover {
  color: #409eff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-box {
  margin-right: 10px;
}

.notification {
  cursor: pointer;
  color: #5a5e66;
}

.notification:hover {
  color: #409eff;
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #606266;
}

.layout-content {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}
:deep(.el-aside) {
  transition: width 0.3s ease;
}
/* 去除element-plus下拉触发区域的黑色边框 */
.el-dropdown-link:focus {
  outline: none !important;
  box-shadow: none !important;
}
.el-dropdown-link:active {
  outline: none !important;
  box-shadow: none !important;
}
</style>
